<template>
  <div class="stats-container">
    <plan-trend-chart @trackEvent="trackEventHandler" :chart-type="type" v-if="type === 'task-trend'"></plan-trend-chart>

    <div class="stats-row" v-if="type === 'task-calendar'"> 
      <div class="stats-panel stats-panel-calendar" ref="calendar">
        <div class="stats-panel-head" :class="isCalendar?'stats-panel-head2':''">
          <h3 class="stats-panel-title">{{ $t('report.statistics.title32') }}
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('common.base.usualStatus.unFinish')}}：{{ $t('report.product.title6') }}</li>
                <li>{{$t('common.base.usualStatus.finish')}}：{{ $t('report.product.title7') }}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </h3>
          <div class="calendar-head">
            <button type="button" @click="adjustMonth(-1)">&lt;&lt;</button>
            <span>{{currentMonth}}</span>
            <button type="button" @click="adjustMonth(1)">&gt;&gt;</button>
          </div> 
          <biz-team-select class="stats-team-select biz-team-select stats-tags-select1" is-auto-select-child collapse multiple :value="tag" @input="chooseTeam" :fetch-func="fetchTeam"/>
          <el-select 
            v-if="isCalendar"
            :placeholder="$t('report.product.title8')" 
            :value="planTimeType" 
            @input="choosePlanTimeType" 
            class="stats-team-select stats-tags-select2">
            <el-option :label="$t('common.task.flow.planStartTime')" value="1"></el-option>
            <el-option :label="$t('common.task.flow.planFinishTime')" value="2"></el-option>
          </el-select>
          <!-- <select @change="chooseTeam">
            <option value="">全部</option>
            <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
          </select> -->
        </div>
        <div class="stats-panel-body" >
          <div class="stats-panel-reference" v-if="isCalendar">
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('common.base.usualStatus.unFinish')}}：{{playTimeText}}</li>
                <li>{{$t('common.base.usualStatus.finish')}}：{{playTimeText}}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </div>
          <div id="calendar"></div>
        </div>
      </div>
      <div class="stats-panel" ref="dailyTable">
        <div class="stats-panel-head ">
          <h3>{{formatDate(day, 'YYYY-MM-DD')}} {{stateName}}</h3>
        </div>
        <div class="stats-panel-body stats-daily-table-wrap">
          <el-table
            class="stats-plan-table"
            :data="dailyTaskRows"
            height="470"
            border
            @header-dragend="handleTableChangeColumnWidth"
          >
            <el-table-column
              v-for="column of dailyTaskColumns"
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              :resizable="column.resizable !== false"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">
                <template v-if="column.field === 'taskNo'">
                  <!-- 工单编号 -->
                  <div>
                    <el-tooltip
                      v-if="row.isGuideData"
                      :content="$t('common.base.tip.sampleTooltip')"
                      placement="top"
                    >
                      <div class="superscript"></div>
                    </el-tooltip>
                    <a
                      :class="row.isGuideData && 'sample-tooltip-content-padding'"
                      :href="`/task/view/${row.id}`"
                      :data-id="row.id"
                      @click.prevent="(event) => openTask(event, row)"
                    >
                      {{row.taskNo}}
                    </a>
                  </div>
                </template>

                <template 
                  v-else-if="column.field === 'executorName'"
                >
                  <!-- 负责人 -->
                  <open-data v-if="isOpenData" type="userName" :openid="row.executorStaffId"></open-data>
                  <span v-else>{{ row.executorName }}</span>
                </template>

                <template 
                  v-else-if="column.field === 'state'"
                >
                  <!-- 状态 -->
                  <span class="stats-badge font-12-i" :style="{ backgroundColor: row.stateBg }">
                    {{ row.stateStr }}
                  </span>
                </template>

                <template v-else>
                  {{ row[column.field] }}
                </template>
              </template>
            </el-table-column>

          </el-table>
        </div>
      </div>
    </div>

    <plan-map @trackEvent="mapTrackEventHandler" :chart-type="type" v-if="type === 'task-map'"></plan-map>
  </div>
</template>

<script>
import { isCalendar } from '@src/util/CalendarUtil';
import { openAccurateTab } from '@src/util/platform';
import { formatDate, rangeOfMonth, getTimestamp, dayTimeStart, dayTimeEnd } from 'pub-bbx-utils';  
import moment from 'moment'
import http from 'src/util/HttpUtil';       
import { storageGet, storageSet } from '@src/util/storage.ts'

import TaskStateEnum from '@model/enum/TaskStateEnum'

import calendar from './calendar';
import PlanMap from './PlanMap.vue'; 
import PlanTrendChart from './PlanTrendChart.vue';
import SampleTooltip from 'packages/SampleTooltip';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

const tableColumnsWidthStorageKey = 'stats-plan-view-table-columns-width';
const storageModule = 'report'

export default {
  name: 'stats-plan-view',
  data() {
    return {
      tag: [],
      msec: +new Date(),
      calendarStartTime: '',
      calendarEndTime: '',
      dailyTaskRows: [],
      dailyTaskColumns: [],
      // teams: [],
      teamId: '',

      state: 'unfinished',
      day: '',
      type: '', // 判断入口
      planTimeType:'',
      isCalendar 
    };
  },
  computed: {
    currentMonth() {
      return formatDate(this.msec, 'YYYY-MM');
    },
    stateName(){
      return this.state == 'unfinished' ? this.$t('report.common.taskState.1') : this.$t('report.common.taskState.0');
    },
    playTimeText(){
      return this.planTimeType == '1' ? this.$t('report.product.title9') : this.planTimeType == '2' ? this.$t('report.product.title10') : '';
    }
  },
  methods: {
    formatDate,
    /**
     * 修改表格列宽
     */
    handleTableChangeColumnWidth(newWidth, oldWidth, column, event){
      const { property } = column;
      const targetColumn = this.dailyTaskColumns.find(item => item.field === property);
      targetColumn.width = newWidth;
      const widthMap = this.dailyTaskColumns.reduce((acc, cur) => {
        acc[cur.field] = cur.width;
        return acc;
      }, {});
      storageSet(tableColumnsWidthStorageKey, widthMap, storageModule);
    },
    // 判断判断是否拥有日历功能
    async getSettingCalendar(){
      try {
        // let calendarStatus = await SettingApi.getSettingCalendar();
        // this.isCalendar=calendarStatus.data.status==2;
        this.planTimeType = this.isCalendar ? '1' : '';
      } catch (error) {
        console.error('fetch TaskList.js getSettingCalendar => error', error);
      }
    },
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    chooseTeam(value){
      this.$tdOnEvent('pc：业务计划-工单日历团队选择事件');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      let tag = value;
      this.tag = value;
      this.teamId = tag.map(item => {return item.id}).join(',');

      let range = rangeOfMonth(this.msec);
      this.renderCalendar(range[0], range[1], this.teamId, this.planTimeType);

      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TEAM', this.$track)
    },
    choosePlanTimeType(value){
      this.$tdOnEvent('pc：业务计划-工单日历计划时间类型选择事件');
      this.planTimeType = value;

      let range = rangeOfMonth(this.msec);
      this.renderCalendar(range[0], range[1], this.teamId, this.planTimeType);
    },
    adjustMonth(num){
      this.msec = moment(this.msec).add(num, 'month')
      let range = rangeOfMonth(this.msec);
      this.renderCalendar(range[0], range[1], this.teamId, this.planTimeType);
    },  
    initCanlendar() {
      let range = rangeOfMonth(this.msec);
      const calendarEl = document.getElementById('calendar')
      if(!calendarEl) return
      calendar.init(document.getElementById('calendar'), this);
      calendar.chart.on('click', event => {
        let origin = event.data._origin;
        let state = '';
        if(event.name == this.$t('common.base.usualStatus.unFinish')) state = 'unfinished';
        if(event.name == this.$t('common.base.usualStatus.finish')) state = 'finished';

        this.renderDailyTaskTable(+dayTimeStart(origin.dateTime), state, this.planTimeType);
      })

      this.renderCalendar(range[0], range[1], this.teamId, this.planTimeType);
      this.renderDailyTaskTable(+dayTimeStart(), 'unfinished', this.planTimeType);
    },
    async renderCalendar(start, end, teamId, planTimeType){
      try {
        let instance = this.$loading.show(this.$refs.calendar);

        let data = await this.fetchCalendarData(start, end, teamId, planTimeType);

        instance.hide();
        calendar.render(start, end, data);
      } catch (error) {
        console.log(error)
      }
    },
    fetchCalendarData(timeStart, timeEnd, teamId, planTimeType){
      let params = {
        timeStart: getTimestamp(timeStart),
        timeEnd: getTimestamp(timeEnd),
        tagId: teamId,
        planTimeType
      };
      return http.post('/api/report/outside/stats/plan/calendar', params)
    },
    async renderDailyTaskTable(day, state, planTimeType){
      try {
        this.state = state;
        this.day = day;

        let instance = this.$loading.show(this.$refs.dailyTable);
        let data = await this.fetchDailyTask(day, state, planTimeType);

        this.dailyTaskRows = (data || []).map(item => {
          if(item.state){
            item.stateStr = TaskStateEnum.getName(item.state)
            item.stateBg = TaskStateEnum.getColor(item.state)
          }
          return item
        })

        instance.hide();
      } catch (error) {
        console.log(error)
      }
    },
    fetchDailyTask(day, state, planTimeType){
      let params = {
        timeStart: +dayTimeStart(day),
        timeEnd: +dayTimeEnd(day),
        state,
        teamId: this.teamId,
        planTimeType
      }

      return http.post('/api/report/outside/stats/plan/dailyTask', params);
    },
    async buildDailyTaskColumns(){
      const cacheColumns = await storageGet(tableColumnsWidthStorageKey, {}, storageModule);

      this.dailyTaskColumns =  [
        {
          label: this.$t('common.label.taskNo'),
          field: 'taskNo',
          width: cacheColumns.taskNo,
          minWidth: 128,
        },
        {
          label: this.$t('common.label.taskTemplate'),
          field: 'templateName',
          width: cacheColumns.templateName,
          minWidth: 128,
        },
        {
          label: this.$t('common.customer.customerName'),
          field: 'customerName',
          width: cacheColumns.customerName,
          minWidth: 128,
        },
        {
          label: this.$t('common.label.customerAddress'),
          field: 'address',
          width: cacheColumns.address,
          minWidth: 128,
        },
        {
          label: this.$t('common.label.principalName'),
          field: 'executorName',
          width: cacheColumns.executorName,
          minWidth: 128,
        },
        {
          label: this.$t('common.base.status'),
          field: 'state',
          width: cacheColumns.state,
          minWidth: 128,
          resizable: false,
        }
      ]
    },
    openTask(event, row){
      event.preventDefault();
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `taskView_${ row.id}`, 
      //   title: `工单${row.taskNo}`,
      //   close: true, 
      //   url: `/task/view/${ row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: row.id,
        titleKey: row.taskNo,
        fromId
      })
    },
    // TalkingData埋点事件
    trackEventHandler(type) {
      switch (type) {
      case 'chooseTeam':
        this.$tdOnEvent('pc：业务计划-工单趋势图团队选择事件');
        break;
      case 'chooseDate':
        this.$tdOnEvent('pc：业务计划-日期选择事件');
        break;
      default:
        break;
      }
    },
    mapTrackEventHandler(type) {
      switch (type) {
      case 'chooseTeam':
        this.$tdOnEvent('pc：业务计划-未完成工单团队选择事件');
        break;
      default:
        break;
      }
    }
  },
  mounted() {
    this.buildDailyTaskColumns(),

    this.getSettingCalendar();
    this.type = window.location.href.split('type=')[1]
    // let initData = window._init_data || {};
    // this.teams = initData.teams || [];
    // 加载日历
    try{
      this.$nextTick(() => this.initCanlendar());
    }catch(e){
      console.log('plan.PlanView', e);
    }
  },
  components: {
    [PlanMap.name]: PlanMap,
    [PlanTrendChart.name]: PlanTrendChart,
    [SampleTooltip.name]: SampleTooltip,
  }
};
</script>

<style lang="scss">
.stats-panel-calendar {
  flex-grow: 0.6 !important;
  min-width: 480px;
  
  .stats-panel-head{
    position: relative;
    padding-left: 110px;

    h3{
      position: absolute;
      top: 6px;
      left: 6px;
    }

    .stats-tags-select1{
      position: absolute;
      top: 2px;
      right: 6px;
      width: 200px;
      .biz-team-select-tag-text{
        max-width: 90px;
      }
    }
    .stats-tags-select2{
      display: none;
      position: absolute;
      top: 2px;
      right: 6px;
      width: 120px;
    }
  }
  .stats-panel-head2{
    padding-left: 210px;
    .stats-panel-title{
      display: none;
    }
    .stats-tags-select1{
      left:6px;
      right: initial;
    }
    .stats-tags-select2{
      display: block;
    }
  }
}

.calendar-head{
  width: 140px;
  display: flex;
  flex-flow: row nowrap;

  span{
    display: block;
    width: 88px;
    font-size: 14px;
    text-align: center;
    color: #000;
    line-height: 26px;
  }

  button{
    background-color: transparent;
    border: none;
    width: 26px;
    line-height: 26px;
    text-align: center;
    padding: 0;
    border-radius: 2px;
    transition: all ease .15s;
    font-weight: 600;
    outline: none;

    &:hover{
      color: #337ab7;
      background-color: #f0f0f0;
    }
  }
}

#calendar {
  margin: 0 auto;
  width: 480px;
  height: 460px;
}

#trend {
  height: 400px;
  margin: 0 auto;
}

.stats-daily-table-wrap {
  height: 495px;
  width: calc(100% - 24px);
  .stats-plan-table{
    margin: 12px;
    // width: calc(100% - 24px);
    &.el-table--border {
      border-top: 1px solid #EBEEF5;
      border-left: 1px solid #EBEEF5;
    }

    .el-table__header th.el-table__cell{
      background-color: #fafafa;

      th{
        line-height: 28px;
      }
    }
  }
}
.stats-daily-table-wrap {
  .base-table-cell {
    height: auto;
  }
}
.stats-panel-reference{
  position: absolute;
  top: 6px;
  left: 6px;
  display: inline-block;
  z-index:20;
}
.customer-name-style {
  width: 100px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
